package net.bioteam.perl5;

/**
 * Wrapper call to call the Perl JNI inplementation. All its methods are synchronized
 *  to ensure there are no thread issue. 
 * @author jason
 * 
 */
public class Perl {
	static {
		try {
			System.loadLibrary("bioteampl");
			Bioteampl.pl_start();
		} catch (UnsatisfiedLinkError e) {
			System.err.println("failed in loading bioteampl library" + e);
			throw new RuntimeException(e);
		}
	}

	/**
	 * Code is evaluated in scalar context. If you expect a boolean value, empty string or string 0 
	 * stands for false value.
	 * @param code the code to be evaluated.
	 * @return scalar result.
	 * @throws Exception
	 * @seealso eval_Boolean
	 */
	public synchronized static String eval(String code) throws Exception {
		String ret = Bioteampl.pl_eval(code);
		String error = Bioteampl.pl_error();
		if (error != null && error.length() > 0) {
			throw new Exception(error);
		}

		return ret;
	}

	/**
	 * short handy method to convert the return string in a boolean value.
	 * Only useful if you expects a boolean value.
	 * @param code
	 * @return a boolean value
	 * @throws Exception
	 */
	public synchronized static boolean evalBoolean(String code)
			throws Exception {
		String ret = Bioteampl.pl_eval(code);
		String error = Bioteampl.pl_error();
		if (error != null && error.length() > 0) {
			throw new Exception(error);
		}
		if (ret.length() == 0)
			return false;
		if (ret.equals("0"))
			return false;
		return true;
	}

	public synchronized static void exit() {
		Bioteampl.pl_stop();
	}
}
